import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class ScanFramePainter extends CustomPainter {
  // 百分比值，0 ~ 1，然后计算Y坐标
  final double lineMoveValue;
  //定义扫描区域
  late Size frameSize;
  final double cornerWidthLength = 12.0;
  final double cornerHeightLength = 10.5;

  ScanFramePainter({required this.lineMoveValue})
      : assert(lineMoveValue != null);

  @override
  void paint(Canvas canvas, Size size) {
    frameSize = size;
    double leftTopX = 0, leftTopY = size.height;

    //根据左上角的坐标和扫描框的大小可得知扫描框矩形
    var rect = Rect.fromLTWH(0, 0, size.width, size.height / 2);
    // 4个点的坐标
    Offset leftTop = rect.topLeft;
    Offset leftBottom = rect.bottomLeft;
    Offset rightTop = rect.topRight;
    Offset rightBottom = rect.bottomRight;

    Paint paint = Paint();

    // paint
    //   ..color = Colors.white
    //   ..strokeWidth = 2.0
    //   ..strokeCap = StrokeCap.square // 解决因为线宽导致交界处不是直角的问题
    //   ..style = PaintingStyle.stroke;
    // print('lineMoveValue  $lineMoveValue');
    //修改画笔线条宽度

    // 扫描线的移动值
    var lineY = frameSize.height * lineMoveValue;

    paint
      ..strokeWidth = 2
      ..color = Color(0xFF0F6EFF);

    // 10 为线条与方框之间的间距，绘制扫描线
    canvas.drawLine(
      Offset(leftTopX, rightTop.dy + lineY),
      Offset(rightTop.dx, rightTop.dy + lineY),
      paint,
    );

    paint.shader = ui.Gradient.linear(
      Offset(size.width / 2, 0),
      Offset(size.width / 2, size.height / 2),
      [
        const Color(0xFF01396F).withOpacity(0.5),
        const Color(0x001C568D).withOpacity(0),
      ],
    );
    canvas.drawRect(
      Rect.fromLTWH(0, lineY, size.width, size.height / 2),
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
